import sharp from "sharp";

import path from "path";
import fs from "fs";

import imagemin from "imagemin";
import imageminMozjpeg from "imagemin-mozjpeg";
import imageminPngquant from "imagemin-pngquant";
export const imgUpload = async (image) => {
    // 1. 查数据库获取用户

    let imgSourcePath = image.filepath;
    let imgDistPath = path.resolve(process.cwd(), `public/uploads/images`);
    // 确保目录存在
    if (!fs.existsSync(imgDistPath)) {
        fs.mkdirSync(imgDistPath);
    }
    const imgDestPath = path.join(imgDistPath, image.newFilename);
    const extName = path.extname(imgSourcePath)?.substring(1);

    // 压缩图片;
    await sharp(imgSourcePath)
        .toFormat(extName, { quality: 10 }) // 设置压缩质量，1-100
        .toFile(imgDestPath, (err, info) => {
            if (err) {
                console.log("An error occurred:", err);
                // reject(err);
                return;
            }

            // resolve(imgDestPath);
        });

    // const buffer = fs.readFileSync(image.filepath);
    // const optimizedBuffer = await imagemin.buffer(buffer, {
    //     plugins: [imageminMozjpeg(), imageminPngquant({ quality: [0.6, 0.8] })]
    // });

    // await fs.writeFileSync(imgDestPath, optimizedBuffer);
    // console.log("Buffer压缩完成");
};
